<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <svg id="svg"></svg>
</body>

</html>
<script src="http://d3js.org/d3.v6.min.js"></script>
<script>
  let width = 600,
    height = 400,
    offset = 50;
  let svg = d3.select('#svg').attr('width', width).attr('height', height);
  let g = svg.append('g');
  let data = [10, 23, 32, 34, 54, 42, 21, 15, 19];


// 创造一个渐变色
let defs = svg.append('defs');
let linearGradient = defs.append('linearGradient')
  .attr('id','color')
  .attr('x1','0%')
  .attr('y1','0%')
  .attr('x2','0%')
  .attr('y2','100%')

  let stop1 = linearGradient.append('stop')
  .attr('offset','0%')
  .attr('stop-color','red')
  .attr('stop-opacity','0.8')

  let stop2 = linearGradient.append('stop')
  .attr('offset','100%')
  .attr('stop-color','red')
  .attr('stop-opacity','0.1')


  // 创建 x 比例尺
  console.log(d3.range(data.length))
  let xScale = d3.scaleBand().domain(d3.range(data.length)).range([0, width - offset * 2])
  // 创造x轴
  let xAxis = d3.axisBottom(xScale)
  g.append('g').call(xAxis).attr(`transform`, `translate(${offset},${height-offset})`)

  // 创建 y 比例尺
  let yScale = d3.scaleLinear().domain([0, d3.max(data) + 20]).range([height - offset * 2, 0])
  // .nice()
  // 创造y轴
  let yAxis = d3.axisLeft(yScale)
  g.append('g').call(yAxis).attr(`transform`, `translate(${offset},${offset})`)

  // 创造线
let area = d3.area().x(function(d,i){
  return xScale(i) + offset + (width-offset*2)/data.length/2
})
.y0(function(d,i){
  return height - offset
})
.y1(function(d,i){
  return yScale(d) + offset
})
.curve(d3.curveCatmullRom )
g.append('path').attr('d',area(data))
.attr('stroke','#333')
// .attr('fill','red')
.attr('fill',`url(#color)`)
.attr('stroke-width',0)

// 线上的点
// g.append('g').selectAll('circle').data(data).enter()
// .append('circle')
// .attr('cx',function(d,i){
//   return xScale(i) + offset + (width-offset*2)/data.length/2
// })
// .attr('cy',function(d,i){
//   return yScale(d) + offset
// })
// .attr('r',6)
// .attr('fill','blue')

// 线上的字
g.append('g').selectAll('text').data(data).enter()
.append('text')
.attr('x',function(d,i){
  return xScale(i) + offset + (width-offset*2)/data.length/2
})
.attr('y',function(d,i){
  return yScale(d) + offset - 10
})
.attr('text-anchor','middle')
.text(function(d,i){
  return d
})
</script>